package com.fantastic.aspect;

import com.fantastic.anno.ResubmitCheck;
import com.fantastic.utils.IpHelperUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Objects;

/**
 * @author : fantastic
 * @date : 2024/5/17 15:30
 * @desc : this class for xxxxx
 **/
@Component
@Aspect
@Slf4j
public class ResubmitAspect {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;



    @Pointcut("@annotation(com.fantastic.anno.ResubmitCheck)")
    public void pointcut() throws Throwable {

    }

    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        ResubmitCheck resubmitCheck = method.getAnnotation(ResubmitCheck.class);
        //过期时间
        int expire = resubmitCheck.expire();
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        //获取请求IP
        String ipAddress = IpHelperUtil.getIpAddress();
        //设置校验的key（业务中可以按照用户信息+方法）
        String resubmitCheckKey = ipAddress + ":" + className + methodName;
        log.info("幂等性key={}",resubmitCheckKey);
        Boolean isResubmit = redisTemplate.opsForValue().setIfAbsent(resubmitCheckKey, "1", Duration.ofSeconds(expire));
        if (Objects.isNull(isResubmit) || !isResubmit) {
            throw new RuntimeException("请勿频繁操作");
        }
    }
}
